package net.hserver.apm.plugin.filter;

import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import cn.hserver.core.interfaces.ResponseAdapter;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.queue.HServerQueue;
import cn.hserver.core.server.context.ConstConfig;
import cn.hserver.core.server.context.HServerContextHolder;
import cn.hserver.core.server.context.Webkit;
import cn.hserver.core.server.util.PropUtil;
import net.hserver.apm.common.DataConfig;
import net.hserver.apm.common.entity.RequestInfo;

@Bean
public class ApmRespFilter implements ResponseAdapter {

    private final static Boolean isRequest = PropUtil.getInstance().getBoolean("amp.request");


    @Override
    public String result(String s) {
        return s;
    }

    @Override
    public FullHttpResponse response(FullHttpResponse fullHttpResponse) {
        if (isRequest) {
            Webkit webKit = HServerContextHolder.getWebKit();
            if (webKit != null) {
                HttpMethod requestType = webKit.httpRequest.getRequestType();
                if (requestType == HttpMethod.GET || requestType == HttpMethod.POST || requestType == HttpMethod.PUT || requestType == HttpMethod.DELETE) {
                    RequestInfo requestInfo = new RequestInfo();
                    requestInfo.setAppName(ConstConfig.APP_NAME);
                    requestInfo.setIp(webKit.httpRequest.getIpAddress());
                    requestInfo.setChainId(webKit.httpRequest.getRequestId());
                    requestInfo.setHeader(webKit.httpRequest.getHeaders().toString());
                    requestInfo.setMethod(webKit.httpRequest.getRequestType().name());
                    if (webKit.httpRequest.getMultipartFile().size() == 0) {
                        requestInfo.setRaw(webKit.httpRequest.getRawData());
                    } else {
                        requestInfo.setRaw("上传文件数据不记录");
                    }
                    requestInfo.setParameter(webKit.httpRequest.getRequestParams().toString());
                    requestInfo.setUri(webKit.httpRequest.getNettyUri());
                    requestInfo.setTime(System.currentTimeMillis());
                    requestInfo.setStatusCode(fullHttpResponse.status().code());
                    requestInfo.setMs((int) (System.currentTimeMillis() - webKit.httpRequest.getCreateTime()));
                    HServerQueue.sendQueue("APM_SEND", DataConfig.APM_DATA_REQUEST_INFO, requestInfo);
                }
            }
        }
        return fullHttpResponse;
    }
}
